<template>
  <div class="create_event">
    <el-row :gutter="20" class="gl_mb_15">
      <el-col :span="24">
        <el-button type="primary" size="mini" @click="openAddEvent()">新增项目</el-button>
        <el-button type="primary" size="mini" @click="openEventTemplate()">导入项目模板</el-button>
      </el-col>
    </el-row>
    <el-table
      v-loading="tableLoading"
      class="gl_my_5"
      :data="tableData"
      stripe
      size="mini"
      style="width: 100%"
      :expand-row-keys="expandRowKeys"
      :row-key="getRowKeys"
    >
      <el-table-column type="expand" :width="40" style="padding: 5px;">
        <template v-if="row.eventGroups" slot-scope="{ row }">
          <el-table :data="row.eventGroups" :show-header="false" size="mini" style="width: 100%">
            <el-table-column label="组别名称" align="center" :width="280">
              <template slot-scope="scope">
                <div>{{ scope.row.name }}</div>
                <div>({{ scope.row.startBirthDate && scope.row.startBirthDate.substring(0, 10) }} - {{ scope.row.endBirthDate && scope.row.endBirthDate.substring(0, 10) }})</div>
              </template>
            </el-table-column>
            <el-table-column prop="levelName" label="具体级别" :mn-width="280">
              <template slot-scope="scope">
                <template v-if="scope.row.events.length && (scope.row.events[0].genderCode === 'M' || scope.row.events[0].genderCode === 'W')">
                  <div>
                    男子组：
                    <template v-for="(eventItem, eventIndex) in scope.row.events">
                      <span v-if="eventItem.genderCode === 'M' && eventItem.name" :key="eventIndex" class="event_item" @click="openUpdateEventName(eventItem, row)">{{ eventItem.name }}
                        <template v-if="eventItem.weightClasses.length > 0">
                          {{ eventItem.weightClasses.length > 0 ? '(' : '' }}
                          <span v-for="(jtem, jndex) in eventItem.weightClasses" :key="jndex">
                            {{ jtem.name }}{{ jndex == eventItem.weightClasses.length-1 ? '' : ',' }}
                          </span>
                          {{ eventItem.weightClasses.length > 0 ? ')' : '' }}
                        </template>
                      </span>
                    </template>
                    <span v-if="row.hasGroup && row.preEventTypeCode !== 'CompetitiveTeam' && row.preEventTypeCode !== 'MixedCompetitiveTeam'" class="event_item add" @click="openCreatEvent(scope.row.id, 'M')">+</span>
                  </div>
                  <div>女子组：
                    <template v-for="(eventItem, eventIndex) in scope.row.events">
                      <span v-if="eventItem.genderCode === 'W' && eventItem.name" :key="eventIndex" class="event_item" @click="openUpdateEventName(eventItem, row)">{{ eventItem.name }}
                        <template v-if="eventItem.weightClasses.length > 0">
                          {{ eventItem.weightClasses.length > 0 ? '(' : '' }}
                          <span v-for="(jtem, jndex) in eventItem.weightClasses" :key="jndex">
                            {{ jtem.name }}{{ jndex == eventItem.weightClasses.length-1 ? '' : ',' }}
                          </span>
                          {{ eventItem.weightClasses.length > 0 ? ')' : '' }}
                        </template>
                      </span>
                    </template>
                    <span v-if="row.hasGroup && row.preEventTypeCode !== 'CompetitiveTeam' && row.preEventTypeCode !== 'MixedCompetitiveTeam'" class="event_item add" @click="openCreatEvent(scope.row.id, 'W')">+</span>
                  </div>
                </template>
                <template v-else>
                  <div>
                    具体级别：
                    <template v-for="(eventItem, eventIndex) in scope.row.events">
                      <span v-if="eventItem.name" :key="eventIndex" class="event_item" @click="openUpdateEventName(eventItem, row)">{{ eventItem.name }}
                        <template v-if="eventItem.weightClasses.length > 0">
                          {{ eventItem.weightClasses.length > 0 ? '(' : '' }}
                          <span v-for="(jtem, jndex) in eventItem.weightClasses" :key="jndex">
                            {{ jtem.name }}{{ jndex == eventItem.weightClasses.length-1 ? '' : ',' }}
                          </span>
                          {{ eventItem.weightClasses.length > 0 ? ')' : '' }}
                        </template>
                      </span>
                    </template>
                    <span
                      v-if="row.hasGroup && row.preEventTypeCode !== 'CompetitiveTeam' && row.preEventTypeCode !== 'MixedCompetitiveTeam'"
                      class="event_item add"
                      @click="openCreatEvent(scope.row.id, scope.row.events[0] && scope.row.events[0].genderCode || 'N')"
                    >+</span>
                  </div>
                </template>
              </template>
            </el-table-column>
            <el-table-column :label="$t('table.actions')" :width="330">
              <template slot-scope="scope">
                <el-button size="mini" type="text" @click="openEditEventGroup(scope.row)">编辑</el-button>
                <el-button size="mini" type="text" @click="deleteEventGroup(scope.row)">
                  <span class="gl_color_error">{{ $t('table.delete') }}</span>
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="项目名称" :min-width="280" />
      <el-table-column prop="systemName" label="项目制度" :width="220">
        <template slot-scope="{ row }">
          {{ row.eventType && row.eventType.name }}
        </template>
      </el-table-column>
      <el-table-column prop="typeName" label="项目类型" :width="220">
        <template slot-scope="{ row }">
          {{ row.registerType && row.registerType.name }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.actions')" :width="300">
        <template slot-scope="{ row }">
          <el-button size="mini" type="text" @click="opeAddEventGroup(row)">添加组别</el-button>
          <el-button size="mini" type="text" @click="openEditEvent(row)">编辑</el-button>
          <el-button size="mini" type="text" @click="deleteEvent(row)">
            <span class="gl_color_error">{{ $t('table.delete') }}</span>
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-row style="text-align: center;" class="gl_pb_15">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="api_GET_EventsManagementCategoryQO.MaxResultCount"
        :current-page="api_GET_EventsManagementCategoryQO.page"
        @size-change="changePageSize"
        @current-change="changePage"
      />
    </el-row>

    <add-event ref="addEvent" @refreshPage="getEventList(api_GET_EventsManagementCategoryQO.Page)" />
    <choose-event-template ref="editEventTemplate" @openAddEvent="openAddEvent" />
    <add-event-group ref="addEventGroup" @refreshPage="getEventList(api_GET_EventsManagementCategoryQO.Page)" />
    <edit-event ref="editEvent" :has-sub-competition="hasSubCompetition" @refreshPage="getEventList(api_GET_EventsManagementCategoryQO.Page)" />
    <edit-event-group ref="editEventGroup" :has-sub-competition="hasSubCompetition" @refreshPage="getEventList(api_GET_EventsManagementCategoryQO.Page)" />
    <el-dialog :title="updateLevelNameTypeCode === 'add' ? '新增级别' : '编辑级别'" width="660px" class="gl_dialog_TitleLine" :close-on-click-modal="false" :visible.sync="updateLevelNameDialog">
      <el-form ref="categoryVO" :rules="eventGroupsVO_Rules" label-width="140px" :model="categoryVO">
        <el-form-item label="级别名称" prop="name" size="mini">
          <el-input v-model="categoryVO.name" style="width: 80%;" />
        </el-form-item>
        <el-form-item v-if="hasWeightClasses" label="级别拆分" prop="weightClassNames" size="mini">
          <el-row>
            <el-col v-for="(item, index) in updateEventLevelItem.weightClasses" :key="index" :span="7" class="form_item_Section">
              <el-input
                v-model.trim="categoryVO.weightClassNames[index]"
                placeholder="请填写"
                class="form_item_input"
              />
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <template v-if="updateLevelNameTypeCode === 'edit' && !hasWeightClasses">
          <el-button size="mini" type="danger" @click="deleteEventLevel">删除</el-button>
        </template>
        <template v-if="updateLevelNameTypeCode === 'add'">
          <el-button size="mini" type="default" @click="updateLevelNameDialog = false">取消</el-button>
        </template>
        <el-button size="mini" type="primary" :loading="updateEventNameLoading" @click="updateEventName">{{ $t('button.save') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import addEvent from './addEvent';
import chooseEventTemplate from './chooseEventTemplate';
import addEventGroup from './addEventGroup';
import editEvent from './editEvent';
import editEventGroup from './editEventGroup';
import { SiSTKWEventsManagementUpdateEventInput_Rules } from '@/lib/validate/events';
import { Api_GET_EventsManagementCategoryQO, SiSTKWEventsManagementUpdateEventInput } from '@/lib/form/game/swaggerForm';
import {
  api_GET_EventsManagementCategory,
  api_DELETE_EventsManagementCategoryId,
  api_DELETE_EventsManagementEventGroupId,
  api_PUT_EventsManagementEventId,
  // api_POST_EventsManagementEventIdChangeName,
  api_DELETE_EventsManagementEventId,
  api_POST_EventsManagementEvent,
  api_GET_EventsManagementCompetitionChildren
} from '@/extend/api/gameswaggerApi/app';
import { Api_GET_CompetitionQO } from '@/lib/form/events';
// import { CopyData } from '@/lib';
export default {
  name: 'CreateEvent',
  components: {
    addEvent,
    addEventGroup,
    chooseEventTemplate,
    editEvent,
    editEventGroup
  },
  data() {
    return {
      api_GET_EventsManagementCategoryQO: new Api_GET_EventsManagementCategoryQO(),
      categoryVO: new SiSTKWEventsManagementUpdateEventInput(),
      eventGroupsVO_Rules: new SiSTKWEventsManagementUpdateEventInput_Rules(),
      competitionQO: new Api_GET_CompetitionQO(),
      tableData: [],
      tableLoading: false,
      total: 0,
      expandRowKeys: [],
      // 编辑级别名称相关
      updateLevelNameDialog: false,
      updateEventNameLoading: false,
      deleteEventLoading: false,
      updateLevelNameTypeCode: 'add',
      weightClassNames: [],
      updateEventLevelItem: {},
      hasWeightClasses: false,
      hasSubCompetition: false // 是否有分站赛
    };
  },
  created() {
    this.gameId = this.$route.params.parentId;
    this.init();
    this.getCompetitionChildren();
    this.getEventList();
  },
  methods: {
    init() {
      this.api_GET_EventsManagementCategoryQO = new Api_GET_EventsManagementCategoryQO();
      this.api_GET_EventsManagementCategoryQO.IncludeEventGroup = true;
      this.api_GET_EventsManagementCategoryQO.IncludeEvent = true;
      this.api_GET_EventsManagementCategoryQO.IncludeGender = true;
      this.api_GET_EventsManagementCategoryQO.IncludeEventType = true;
      this.api_GET_EventsManagementCategoryQO.IncludeRegisterType = true;
      this.api_GET_EventsManagementCategoryQO.IncludeCategoryRound = true;
      this.api_GET_EventsManagementCategoryQO.IncludeWeightClasses = true;
      this.api_GET_EventsManagementCategoryQO.CompetitionId = this.gameId;
      this.api_GET_EventsManagementCategoryQO.Sorting = 'creationTime';
    },
    // 获取分站赛列表
    getCompetitionChildren() {
      const _this = this;
      this.competitionQO.HasParent = true;
      this.competitionQO.ParentId = this.gameId;
      this.competitionQO.TypeCode = 'League';
      this.competitionQO.MaxResultCount = 1;
      api_GET_EventsManagementCompetitionChildren(this.competitionQO).then(res => {
        const _Data = res.items || [];
        _this.hasSubCompetition = _Data.length > 0;
        console.log('hasSubCompetition', _this.hasSubCompetition);
      }, (error) => {
        this.tableLoading = false;
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    // 确定唯一的key值
    getRowKeys(row) {
      return row.id;
    },
    getEventList(page) {
      const _this = this;
      this.tableLoading = true;
      this.api_GET_EventsManagementCategoryQO.Page = page || 1;
      this.api_GET_EventsManagementCategoryQO.SkipCount = (this.api_GET_EventsManagementCategoryQO.Page - 1) * this.api_GET_EventsManagementCategoryQO.MaxResultCount;
      api_GET_EventsManagementCategory(this.api_GET_EventsManagementCategoryQO).then(res => {
        this.tableData = res.items || [];
        for (let i = 0; i < _this.tableData.length; i++) {
          const item = _this.tableData[i];
          for (let j = 0; j < item.eventGroups.length; j++) {
            const jtem = item.eventGroups[j];
            jtem.events = jtem.events.sort((a, b) => a.sortOrder - b.sortOrder);
            for (let k = 0; k < jtem.events.length; k++) {
              const ktem = jtem.events[k];
              ktem.weightClasses = ktem.weightClasses.sort((a, b) => a.sortOrder - b.sortOrder);
            }
          }
        }
        this.total = res.totalCount;
        this.tableLoading = false;
      }, (error) => {
        this.tableLoading = false;
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    // 删除项目
    deleteEvent(eventInfo) {
      this.$confirm(`您确定要删除吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableLoading = true;
        api_DELETE_EventsManagementCategoryId(eventInfo.id).then(() => {
          this.getEventList(this.api_GET_EventsManagementCategoryQO.Page);
          this.$message({ type: 'success', message: '删除成功！' });
        }, (error) => {
          this.tableLoading = false;
          const _msg = error.error.message || error.message;
          this.$message({ type: 'error', message: _msg });
        });
      }).catch(() => {});
    },
    // 删除组别
    deleteEventGroup(groupInfo) {
      this.$confirm(`您确定要删除吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableLoading = true;
        api_DELETE_EventsManagementEventGroupId(groupInfo.id).then(() => {
          this.getEventList(this.api_GET_EventsManagementCategoryQO.Page);
          this.$message({ type: 'success', message: '删除成功！' });
        }, (error) => {
          this.tableLoading = false;
          const _msg = error.error.message || error.message;
          this.$message({ type: 'error', message: _msg });
        });
      }).catch(() => {});
    },
    openAddEvent(eventInfo) {
      this.$refs.addEvent.open(eventInfo);
    },
    // 编辑项目
    openEditEvent(eventInfo) {
      this.$refs.editEvent.open(eventInfo);
    },
    // 编辑组别
    openEditEventGroup(eventGroupInfo) {
      this.$refs.editEventGroup.open(eventGroupInfo);
    },
    // 编辑级别名称
    openUpdateEventName(eventItem, row) {
      this.updateLevelNameTypeCode = 'edit';
      this.updateEventLevelItem = {};
      this.categoryVO = new SiSTKWEventsManagementUpdateEventInput();
      this.categoryVO.name = eventItem.name;
      this.updateEventLevelItem = eventItem;
      if (this.updateEventLevelItem.weightClasses && this.updateEventLevelItem.weightClasses.length > 0) {
        this.hasWeightClasses = true;
      } else {
        this.hasWeightClasses = false;
      }
      console.log('🚀 ~ file: index.vue ~ line 261 ~ openUpdateEventName ~ this.updateEventLevelItem', this.updateEventLevelItem);
      // this.updateEventLevelRow = row;
      console.log('🚀 ~ file: index.vue ~ line 259 ~ openUpdateEventName ~ this.categoryVO', this.categoryVO);
      this.categoryVO.name = eventItem.name;
      this.categoryVO.weightClassNames = eventItem.weightClasses.map(function(item) {
        return item.name;
      });
      this.updateLevelNameDialog = true;
    },
    openCreatEvent(groupId, genderCode) {
      this.updateLevelNameTypeCode = 'add';
      this.updateEventLevelItem = {};
      this.hasWeightClasses = false;
      this.groupId = groupId;
      this.categoryVO.name = '';
      this.genderCode = genderCode;
      this.updateLevelNameDialog = true;
      this.$nextTick(() => {
        this.$refs.categoryVO.clearValidate();
      });
    },
    updateEventName() {
      const _this = this;
      this.$refs.categoryVO.validate(valid => {
        if (!valid) return;
        this.updateEventNameLoading = true;
        if (this.updateLevelNameTypeCode === 'edit') {
          api_PUT_EventsManagementEventId(this.updateEventLevelItem.id, this.categoryVO).then(() => {
            _this.$message({ type: 'success', message: '修改成功！' });
            _this.updateEventNameLoading = false;
            _this.updateLevelNameDialog = false;
            _this.getEventList(_this.api_GET_EventsManagementCategoryQO.Page);
          }, error => {
            _this.updateEventNameLoading = false;
            const _msg = error.error.message || error.message;
            _this.$message({ type: 'error', message: _msg });
          });
        } else {
          api_POST_EventsManagementEvent({
            name: this.categoryVO.name,
            genderCode: this.genderCode,
            groupId: this.groupId
          }).then(() => {
            _this.$message({ type: 'success', message: '新增成功！' });
            _this.updateEventNameLoading = false;
            _this.updateLevelNameDialog = false;
            _this.getEventList(_this.api_GET_EventsManagementCategoryQO.Page);
          }, error => {
            _this.updateEventNameLoading = false;
            const _msg = error.error.message || error.message;
            _this.$message({ type: 'error', message: _msg });
          });
        }
      });
    },
    deleteEventLevel() {
      this.$confirm(`您确定要删除吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableLoading = true;
        api_DELETE_EventsManagementEventId(this.updateEventLevelItem.id).then(() => {
          this.getEventList(this.api_GET_EventsManagementCategoryQO.Page);
          this.$message({ type: 'success', message: '删除成功！' });
          this.updateLevelNameDialog = false;
        }, (error) => {
          this.tableLoading = false;
          const _msg = error.error.message || error.message;
          this.$message({ type: 'error', message: _msg });
        });
      }).catch(() => {});
    },
    openEventTemplate() {
      this.$refs.editEventTemplate.open();
    },
    opeAddEventGroup(eventInfo) {
      this.$refs.addEventGroup.open(eventInfo);
    },
    changePage(page) {
      this.getEventList(page);
    },
    changePageSize(pagesize) {
      this.api_GET_EventsManagementCategoryQO.MaxResultCount = pagesize;
      this.getEventList();
    },
    sortData (data) {
      // 排序_sortObj
      const _data = data.sort((a, b) => a.sortOrder - b.sortOrder);
      return _data;
    }
  }
};
</script>
<style>
.create_event .el-table__expanded-cell {
  padding: 5px;
}
.create_event .event_item {
  padding: 2px 5px;
  color: #117CDF;
  background: rgba(243, 249, 255, 1);
  margin-right: 10px;
  cursor: pointer;
  border: 1px solid transparent;
}
.create_event .event_item.add {
  padding: 2px 8px;
  color: #666;
  background: #fff;;
  border: 1px solid #eee;
  transition: all 0.3s ease;
}
.create_event .event_item.add:hover {
  color: #117CDF;
  background: rgba(243, 249, 255, 1);
}
.form_item_Section{
  margin: 0 10px 10px 0 ;
}
</style>
